/*  
 * Copyright (c) 2015-2026 LeeSon Ltd. All Rights Reserved.  
 * LeeSon  QQ:25901875
 */
package com.leeson.portal.manage.view.action;

import java.util.HashSet;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.leeson.portal.manage.base.BaseAction;
import com.leeson.portal.manage.domain.Department;
import com.leeson.portal.manage.domain.PageBean;
import com.leeson.portal.manage.domain.Role;
import com.leeson.portal.manage.domain.User;
import com.leeson.portal.manage.utils.DepartmentUtils;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

	private static final long serialVersionUID = -4296032514753579198L;

	private int pageNum=1;  //当前页
    private int pageSize=10;  //每页多少条记录
	private String[] choose;
	
	
	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String[] getChoose() {
		return choose;
	}

	public void setChoose(String[] choose) {
		this.choose = choose;
	}
	
	
	private Long departmentId;
	private Long[] roleIds;

	public Long getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(Long departmentId) {
		this.departmentId = departmentId;
	}

	public Long[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Long[] roleIds) {
		this.roleIds = roleIds;
	}

	/**
	 * 列表（带分页）
	 * 
	 * @return
	 */
	public String list() {
		User searchModel = new User();
		StringBuffer sb = new StringBuffer("where 1=1 ");
		if(model.getName()!=null&&!model.getName().equals("")){
			sb.append(" and name like '%"+model.getName()+"%' ");
			searchModel.setName(model.getName());
		}
		if(model.getId()!=null&&!model.getId().equals("")){
			sb.append(" and id='"+model.getId()+"'");
			searchModel.setId(model.getId());
		}
		if(model.getLoginName()!=null&&!model.getLoginName().equals("")){
			sb.append(" and loginName like '%"+model.getLoginName()+"%' ");
			searchModel.setLoginName(model.getLoginName());
		}
		if(departmentId!=null&&!departmentId.equals("")){
			sb.append(" and departmentId="+departmentId+" ");
			this.setDepartmentId(departmentId);
			Department department=departmentService.getById(departmentId);
			ActionContext.getContext().put("department", department);
		}
		if(model.getDescription()!=null&&!model.getDescription().equals("")){
			sb.append(" and description like '%"+model.getDescription()+"%' ");
			searchModel.setDescription(model.getDescription());
		}
		
		
//		List<Account> userList = accountService.findByCondition(sb.toString());
//		ActionContext.getContext().put("userList", userList);
		
		PageBean pageBean=userService.findByConditionWithPage(pageNum,pageSize,sb.toString());
		ActionContext.getContext().getValueStack().push(pageBean);
		ActionContext.getContext().getValueStack().push(searchModel);
		
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtils
				.getAllDepartments(topList);
		ActionContext.getContext().put("departmentList", departmentList);
		return "list";
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String delete() {
		if(model.getId()==1){
			return "toList";
		}else {
			userService.delete(model.getId());
			return "toList";
		}
		
	}

	/**
	 * 删除多选
	 * 
	 * @return
	 */
	public String deleteChoose() {
		if (choose != null && choose.length > 0) {
			for (int i = 0; i < choose.length; i++) {
				if(!(choose[i].equals("1"))){
					userService.delete(Long.parseLong(choose[i]));
				}
				
			}
		}
			
		return "toList";
	}
	
	/**
	 * 添加页面
	 * 
	 * @return
	 */
	public String addUI() {
		// 准备数据, departmentList
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtils
				.getAllDepartments(topList);
		ActionContext.getContext().put("departmentList", departmentList);
		// 准备数据, roleList
		List<Role> roleList = roleService.list();
		ActionContext.getContext().put("roleList", roleList);
		return "saveUI";
	}

	/**
	 * 添加
	 * 
	 * @return
	 */
	public String add() {
		if(!userService.checkLoginName(model.getLoginName())){
			model.setLoginName("用户名已经存在");
			ActionContext.getContext().getValueStack().push(model);
			ActionContext.getContext().put("msg", "用户名已经存在");
			
			
			// 准备数据, departmentList
			List<Department> topList = departmentService.findTopList();
			List<Department> departmentList = DepartmentUtils
					.getAllDepartments(topList);
			ActionContext.getContext().put("departmentList", departmentList);
			// 准备数据, roleList
			List<Role> roleList = roleService.list();
			ActionContext.getContext().put("roleList", roleList);
			// 准备回显的数据
			
			return "saveUI";
		}
		// 封装到对象中（当model是实体类型时，也可以使用model，但要设置未封装的属性）
		// >> 设置所属部门
		model.setDepartment(departmentService.getById(departmentId));
		// >> 设置关联的岗位
		List<Role> roleList = roleService.getByIds(roleIds);
		model.setRoles(new HashSet<Role>(roleList));
		
		// >> 设置默认密码为1234（要使用MD5摘要）
				String md5Digest = DigestUtils.md5Hex("1234");
				if(!(model.getPassword().equals("")||model.getPassword()==null)){
					md5Digest=DigestUtils.md5Hex(model.getPassword());
				}
				model.setPassword(md5Digest);

		// 保存到数据库
		userService.save(model);
		return "toList";
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	public String editUI() {
		// 准备数据, departmentList
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtils
				.getAllDepartments(topList);
		ActionContext.getContext().put("departmentList", departmentList);
		// 准备数据, roleList
		List<Role> roleList = roleService.list();
		ActionContext.getContext().put("roleList", roleList);
		// 准备回显的数据
		User user = userService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(user);
		if (user.getDepartment() != null) {
			departmentId = user.getDepartment().getId();
		}
		if (user.getRoles() != null) {
			roleIds = new Long[user.getRoles().size()];
			int index = 0;
			for (Role role : user.getRoles()) {
				roleIds[index++] = role.getId();
			}
		}
		return "saveUI";
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public String edit() {
		// 1，从数据库中取出原对象
		User user = userService.getById(model.getId());

        String ps=model.getPassword();
		
		if(!(user.getPassword().equals(ps))&&!(ps.equals("")||ps==null)){
			String md5Digest = DigestUtils.md5Hex(model.getPassword());
			user.setPassword(md5Digest);
		}
		// 2，设置要修改的属性
		user.setLoginName(model.getLoginName());
		user.setName(model.getName());
		user.setGender(model.getGender());
		user.setPhoneNumber(model.getPhoneNumber());
		user.setEmail(model.getEmail());
		user.setDescription(model.getDescription());
		// >> 设置所属部门
		user.setDepartment(departmentService.getById(departmentId));
		// >> 设置关联的岗位
		List<Role> roleList = roleService.getByIds(roleIds);
		user.setRoles(new HashSet<Role>(roleList));

		// 3，更新到数据库
		userService.update(user);

		return "toList";
	}

	/**
	 * 初始化密码
	 * 
	 * @return
	 */
	public String initPassword() {
		userService.initPassword(model.getId());
		return "toList";
	}

	/**
	 * 登陆页面
	 * 
	 * @return
	 */
	public String loginUI() {

		return "loginUI";
	}

	/**
	 * 登陆
	 * 
	 * @return
	 */
	public String login() {
		if(model.getLoginName()==null||model.getLoginName().trim().equals("")||model.getPassword()==null||model.getPassword().trim().equals("")){
			addFieldError("login", "用户名、密码不能为空！");
			return "loginUI";
		}
		User user = userService.findByLoginNameAndPassword(model.getLoginName(), model.getPassword());
		if (user == null) {
			addFieldError("login", "用户名或密码不正确！");
			return "loginUI";
		} else {
			// 登录用户
			ActionContext.getContext().getSession().put("user", user);
			return "toIndex";
		}

	}

	/**
	 * 注销
	 * 
	 * @return
	 */
	public String logout() {
		ActionContext.getContext().getSession().remove("user");
		return "logout";
	}

}
